﻿$(document).ready(function() {
    var savedCity = $.cookie('city');
    if (savedCity)
        changeTown(savedCity);
    if ($("#gift_card").length)
        registerInfoHandlers();
    var form = $("#select_card.standart, #select_card.virtual");
    if (!form.length) return;
    $("div.scroll", form).jScrollPane();
    registerValidators(form);
    registerFormHandler();
    var dateSend = $("input[name=date_send]");
    if (dateSend.length) dateSend.mask("99•99•9999");
    $('input[placeholder], textarea[placeholder]').placeholder();
    registerAdditionalHandlers();
    $(document).click(function(e) {
    if ($(e.target).parents().filter('#select_card .scroll:visible').length == 0) {
        $("#select_card .scroll").removeClass("on");
    }
});
});

function registerInfoHandlers() {
    $("#gift_card .gift_card_info_icon").click(function() {
        if (!$(this).hasClass("on")) {
            $(this).addClass("on");
            $("#gift_card .gift_card_info").show();
        }
    });
    $("#gift_card .gift_card_info .close").click(function() {
        $("#gift_card .gift_card_info_icon").removeClass("on");
        $("#gift_card .gift_card_info").hide();
    });
}

function registerAdditionalHandlers() {
 $("input#sum").live('focus click', function(event) {
        $(this).parent().find(".scroll").addClass("on");
        event.stopPropagation();
        return false;
    });
    $("#select_card .scroll a").live('click', function() {
        var targetInput = $("input#sum", $(this).closest("div.input"));
        targetInput.val($(this).html() + " Р.");
        targetInput.trigger("change");
        $("#select_card .scroll").removeClass("on");

        return false;
    });
}

function registerFormHandler() {
    $("#cert_submit").click(function() {
        if (validateForm()) {
            var self = $(this);
            var form = $("#select_card");
            self.prop("disabled", true);
            $.ajax({
                type: "POST",
                'url': '/certificate/new',
                'data':form.serialize()
            }).done(function(response) {
                var r = JSON.parse(response);
                if (r.success) {
                    var card = $("input[name=pay_method]:checked", form);
                    // виртуальный сертификат - оплата только картой
                    if (card.length == 0)
                        initPayment(r.certificate);
                    // стандартный, выбран способ оплаты картой
                    else if (card.val() == 'card')
                        initPayment(r.certificate);
                    // стандартный - выбран способ оплаты наличными курьеру
                    else
                        generateReturnPage();
                }
                else {
                    self.prop("disabled", false);
                    alert(r.error);
                }
            });
        }
    });
}

function generateReturnPage() {
    $("#select_card").html('').append("<p>Ваш заказ сформирован.</p><a href='/' class='back'><b>На главную</b></a>");
}

function initPayment(certificate) {
    var action = "https://test.paysecure.ru/pay/order.cfm";
    var merchant = 842502;
    var form = $("<form></form>").attr("method", "POST").attr("action", action);
    form.append($("<input/>").attr("type", "hidden").attr("name", "OrderNumber").val(certificate.number));
    form.append($("<input/>").attr("type", "hidden").attr("name", "OrderAmount").val(certificate.amount));
    form.append($("<input/>").attr("type", "hidden").attr("name", "Email").val(certificate.email));
    form.append($("<input/>").attr("type", "hidden").attr("name", "MobilePhone").val(certificate.phone));
    form.append($("<input/>").attr("type", "hidden").attr("name", "Merchant_ID").val(merchant));
    form.append($("<input/>").attr("type", "hidden").attr("name", "OrderCurrency").val("RUB"));
    form.append($("<input/>").attr("type", "hidden").attr("name", "OrderComment").val('Оплата сертификата Costume Code'));
    form.submit();
}

function validateForm() {
    $("#select_card").css("height", $("#select_card").height() - $("span.error").length * 20 + "px");
    $("span.error").remove();
    if ($("input[name=date_send]").length)
        if (!isValidDate($("input[name=date_send]").val(), 'dd•mm•yyyy'))
            $("input[name=date_send]").after($("<span class='error'></span>").text("Введите корректную дату"));

    $("input[name=email], input[name=friend_email]").each(function() {
        if (!isValidEmail($(this).val()))
            $(this).after($("<span class='error'></span>").text("Введите корректный email"));
    });
    var errors = $("span.error");
    $("#select_card").css("height", $("#select_card").height() + errors.length * 20 + "px");
    return errors.length == 0;
}

function registerValidators(form) {
    var changeHandler = function() {
        var disable = false;
        $("input[type=text], textarea", form).each(function() {
            if (!$(this).val()) {
                disable = true;
                return false;
            }
        });
        if (!disable) {
            $("input[type=radio]", form).each(function() {
                var name = $(this).attr("name");
                if (!$("input[type=radio][name=" + name + "]:checked").length) {
                    disable = true;
                    return false;
                }
            });
        }
        $("button.submit", form).prop("disabled", disable);
    };

    $("input, textarea", form).keyup(changeHandler);
    $("input, textarea", form).change(changeHandler);
    changeHandler();
}



function isValidEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function isValidDate(value, userFormat) {

    userFormat = userFormat || 'mm/dd/yyyy';

    var delimiter = /[^mdy]/.exec(userFormat)[0];

    var theFormat = userFormat.split(delimiter);

    var theDate = value.split(delimiter);

    function isDate(date, format) {
        var m, d, y, i = 0, len = format.length, f;
        for (i; i < len; i++) {
            f = format[i];
            if (/m/.test(f)) m = date[i];
            if (/d/.test(f)) d = date[i];
            if (/y/.test(f)) y = date[i];
        }
        return (
                m > 0 && m < 13 &&
                        y && y.length === 4 &&
                        d > 0 &&
                        d <= (new Date(y, m, 0)).getDate()
                        && new Date(y, m, d) >= new Date()
                );
    }

    return isDate(theDate, theFormat);
}

